import home from '@/router/modules/home';

/**
 * 将菜单权限转成name为key的对象
 * @param arr
 * @returns {Object}
 */
function toNameObj(arr) {
    let idObj = {};
    let nameObj = {};
    for (let item of arr) {
        if (item.menuCode && item.menuType === 0) {
            idObj[item.id] = item;
        }
    }
    
    function getNameKey(obj) {
        let key = obj.menuCode;
        if (obj.pId && idObj[obj.pId]) {
            key += `-${getNameKey(idObj[obj.pId])}`;
        }
        return key;
    }
    
    for (let item of arr) {
        if (item.menuCode) {
            nameObj[getNameKey(item)] = item;
        }
    }
    return nameObj;
}

/**
 * 根据菜单权限来过滤路由, 菜单只到二级
 * @param all
 * @param show
 * @returns {Array}
 */
export function filterMenu(all, show) {
    if (!show) {
        return [];
    }
    let nameObj = toNameObj(show);
    let rst = [];
    let parentIndex = -1;
    for (let parent of all) {
        if (!parent.meta.hidden && !nameObj[parent.name]) {
            continue;
        }
        parentIndex++;
        rst.push({
            name: parent.name,
            path: parent.path,
            meta: {
                ...parent.meta,
            },
        });
        if (parent.children && parent.children.length) {
            rst[parentIndex].children = [];
            let itemIndex = -1;
            for (let item of parent.children) {
                let itemName = `${item.name}-${parent.name}`;
                if (!item.meta.hidden && !nameObj[itemName]) {
                    continue;
                }
                itemIndex++;
                rst[parentIndex].children.push({
                    name: item.name,
                    path: item.path,
                    meta: {
                        ...item.meta,
                    },
                });
            }
        }
    }
    rst.unshift(home);
    return rst;
}

/**
 * 获取按钮权限对象
 * @param arr
 * @returns {{}}
 */
export function getButtons(arr) {
    let idObj = {};
    let buttonList = [];
    let buttons = {};
    for (let item of arr) {
        const {id, menuType} = item;
        if (menuType === 0) {
            idObj[id] = item;
        } else {
            buttonList.push(item);
        }
    }
    for (let item of buttonList) {
        const {pId, menuCode} = item;
        const {menuCode: pCode} = idObj[pId];
        if(!Reflect.has(buttons, pCode)){
            buttons[pCode] = {};
        }
        buttons[pCode][menuCode] = true;
    }
    return buttons;
}
